import os

import aiomysql
from tornado import web, ioloop

from demo.chapter05.forms import MessageForm
from demo.chapter05.models import objects, Message


class MainHandler(web.RequestHandler):

    def initialize(self, db):
        self.db = db

    async def get(self, *args, **kwargs):
        message_from = MessageForm()
        return self.render('message.html', message_from=message_from)

    async def post(self, *args, **kwargs):
        message_from = MessageForm(self.request.arguments)
        if message_from.validate():
            # 验证通过，获取具体值并保存
            # name = message_from.name.data
            await objects.create(Message, **message_from.data)

        return self.render('message.html', message_from=message_from)


if __name__ == '__main__':
    base_dir = os.path.dirname(__file__)
    setting = {
        "static_path": os.path.join(base_dir, 'static'),
        'static_url_prefix': "/static/",  # 设置静态文件路径前缀
        'template_path': os.path.join(base_dir, 'templates'),
        'gzip': True,
        'db': {
            "host": "127.0.0.1",
            "port": 3306,
            "user": "root",
            "password": "",
            "db": "messages",
            "charset": "utf8"
        }
    }

    urls = [
        web.URLSpec("/", MainHandler, {"db": setting['db']}, name='index'),
    ]

    app = web.Application(urls, debug=False, **setting)
    app.listen(8000)

    ioloop.IOLoop.current().start()
